import layoutHeaderAside from '@/layout/header-aside'

// 初始化路由菜单
export function initMenu(router) {
  let menus = JSON.parse(localStorage.getItem('menuList')) ? JSON.parse(localStorage.getItem('menuList')) : []
  if (menus.length === 0) {
    return router
  }
  let menuArr = formatRoutes(menus)
  if (menuArr) {
    menuArr.forEach(el => {
      if (!el.children) {
        router[0].children.push(el)
      } else {
        router.push(el)
      }
    })
  }
  return router
}

// 路由处理
export const formatRoutes = (aMenu) => {
  const aRouter = []
  aMenu.forEach(oMenu => {
    const {
      path,
      title,
      icon,
      children,
      component
    } = oMenu
    if (title !== '首页' && path) {
      const oRouter = {
        path: path,
        name: path.replace(/\//g, '-'),
        meta: { auth: true, cache: true, title: title },
        icon: icon
      }
      if (component === 'Layout') {
        oRouter.component = layoutHeaderAside
      } else {
        oRouter.component = resolve => require(['@/views' + component], resolve)
      }

      if (children) {
        oRouter.children = childrenRouter(path, children)
      }
      aRouter.push(oRouter)
    }
  })
  return aRouter
}

/**
 * 子路由处理
 */
function childrenRouter(el = '', list = [], routerArr = []) {
  list.forEach(element => {
    if (element.menuType === 'C') {
      let routers = {
        path: element.path.replace(el + '/', ''),
        name: element.path.replace(/\//g, '-'),
        meta: { auth: true, cache: true, title: element.title },
        icon: element.icon
      }
      routers.component = resolve => require(['@/views' + element.component], resolve)
      routerArr.push(routers)
    } else if (element.menuType === 'M') {
      childrenRouter(el, element.children, routerArr)
    }
  })
  return routerArr
}
